<?php
/**
 * Name: AdminAuthModel.class.php
 * Description:
 * User: DIY
 * Date: 2016/9/6
 * Time: 18:34
 */

namespace Common\Model;

use Think\Model;

class AdminAuthModel extends Model
{

    /*
     * 获取权限列表
     * @param
     * */
    public function getAdminAuthList($data=array(),$limit=20){
        $param = array(
            '1'=>'1'
        );
        if($data['title']){
            $param['title'] = array('like','%'.$data['title'].'%');
        }
        if($data['url']){
            $param['url'] = array('like','%'.$data['url'].'%');
        }
        if($data['hide']!=''){
            $param['hide'] = $data['hide'];
        }
        $auth_list = $this->where($param)->limit($limit)->select();
        return $auth_list;
    }

    /*
     *获取用户权限列表
     *@param admin_user_id
     * return array()
     * */
    public function getAdminAuthListByAdmin($admin_user_id){
        $AdminRoleModel = new AdminRoleModel();
        $role = $AdminRoleModel
            ->alias('p1')
            ->field('p1.rules')
            ->join('LEFT JOIN __ADMIN_USER__ AS p2 ON p2.role_id=p1.id')
            ->where(array('p2.id'=>$admin_user_id))
            ->find();
        $param = array(
            'hide'=>0,
            'id'=>array('in',$role['rules']),
        );
        $menu = $this
            ->where($param)
            ->order('sort desc')
            ->select();
        return $menu;
    }

    /*
     *获取用户菜单树
     *@param admin_user_id
     * return array()
     * */
    public function getAdminAuthTreeByAdmin($admin_user_id){
        $menu = $this->getAdminAuthListByAdmin($admin_user_id);
        return $this->createTree($menu);
    }

    /*
     *获取所有权限统计
     * @param data=array() 查询条件数组
     * return count 数组
     * */
    public function getAdminAuthCount($data=array()){
        $param = array(
            '1'=>'1'
        );
        if($data['title']){
            $param['title'] = array('like','%'.$data['title'].'%');
        }
        if($data['url']){
            $param['url'] = array('like','%'.$data['url'].'%');
        }
        if($data['hide']!=''){
            $param['hide'] = $data['hide'];
        }
        $count = $this->where($param)->count();
        return $count;
    }

    /*
     * 生成树形菜单
     * */
    private function createTree($data,$pid=0){
        $tree = array();
        foreach($data as $k => $v){
            if($v['pid']==$pid){
                unset($data[$k]);
                $child = $this->createTree($data,$v['id']);
                if($child){
                    $v['child'] = $child;
                }
                $tree[] = $v;
            }
        }
        return $tree;
    }



}